'use strict'

const path = require('path')
const fs = require('fs')
const fse = require('fs-extra')
const log = require('@lenovo-cli/log')
const Command = require('@lenovo-cli/command')
const Git = require('@lenovo-cli/git')

class PublishCommand extends Command {
  init() {
    log.verbose('PublishCommand', this._argv, this._cmd)
    // 获取 publish 命令的 options
    this.options = {
      update: this._cmd._optionValues.update,
      token: this._cmd._optionValues.token,
      type: this._cmd._optionValues.type,
      buildCmd: this._cmd._optionValues.buildCmd,
      prod: this._cmd._optionValues.prod,
      sshUser: this._cmd._optionValues.sshUser,
      sshIp: this._cmd._optionValues.sshIp,
      sshPath: this._cmd._optionValues.sshPath,
    }
  }
  async exec() {
    try {
      const startTime = new Date().getTime()
      // publish 初始化检查
      this.prepare()
      // git flow 自动化
      const git = new Git(this.projectInfo, this.options) // _argv可以根据需要传入Git类
      await git.prepare() // 自动化提交准备和代码仓库初始化
      await git.commit() // 自动提交代码
      await git.publish() // 云构建+云发布
      // 云构建和云发布
      const endTime = new Date().getTime()
      log.info('本次发布用时：', (endTime - startTime) / 1000 + ' s')
    } catch (e) {
      log.error(e.message)
      if (process.env.LOG_LEVEL === 'verbose') {
        console.log(e)
      }
    }
  }
  prepare() {
    // 确认项目是npm项目
    const projectPath = process.cwd()
    const pkgPath = path.resolve(projectPath, 'package.json')
    log.verbose('package.json', pkgPath)
    if (!fs.existsSync(pkgPath)) {
      throw new Error('package.json 不存在！')
    }
    // 确认是否包含build命令、name、version等
    const pkg = fse.readJSONSync(pkgPath)
    const { name, version, scripts } = pkg
    if (!name || !version || !scripts || !scripts.build) {
      throw new Error(
        'package.json文件内容不全（需在scriptes中提供build命令！）'
      )
    }
    this.projectInfo = {
      pkgName: name,
      pkgVersion: version,
      pkgDir: projectPath,
    }
  }
}

function init(argv) {
  return new PublishCommand(argv)
}

module.exports = init
module.exports.PublishCommand = PublishCommand
